import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';
import api from '../../../api/index'
Page({
	data: {
		config: {},
		msgList: [],
		conversationID: null
	},
	onLoad(options) {
		this.setData({
			conversationID: 'C2C' +  options.conversationID
		 });
		this.getImLoginsignData()
	},
	// 发起聊天方法
  handleShowChat() {
    // 跳转到单聊
    wx.navigateTo({
      url: `../chat/index?conversationID=C2C${userID}`,
    })
  },

	getImLoginsignData() {
		api.get(`/api/foreign/tencent/im/loginsign`).then(res => {
			if (res && res.length > 0) {
				const imLoginsignData = {
					userID: res[0].userid,
					SDKAPPID: Number(res[0].appid),
					SECRETKEY: res[0].signature,
					EXPIRETIME: Number(res[0].expire)
				}
				this.setData({
					config: imLoginsignData
				})
				this.init_TIM()
			}
		}).catch(error => {
			wx.showToast({
				title: error.faultstring,
				icon: 'none',
				duration: 3000
			})
			return
		})
	},
	init_TIM() {
		const userSig = this.data.config.SECRETKEY 
		wx.$TUIKit = TencentCloudChat.create({
				SDKAppID: this.data.config.SDKAPPID
		})
		wx.$chat_SDKAppID = this.data.config.SDKAPPID;
		wx.$chat_userID = this.data.config.userID;
		wx.$chat_userSig = userSig;
		wx.TencentCloudChat = TencentCloudChat;
		wx.$TUIKit.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
		wx.$TUIKit.registerPlugin({ 'tim-profanity-filter-plugin': TIMProfanityFilterPlugin });
		wx.$TUIKit.login({
				userID: this.data.config.userID,
				userSig
		});
		wx.setStorage({
				key: 'currentUserID',
				data: [],
		});
		wx.$TUIKit.on(wx.TencentCloudChat.EVENT.SDK_READY, this.onSDKReady,this);
	},
	onUnload() {
		wx.$TUIKit.logout().then((imResponse) =>{
			console.log(imResponse.data); // 登出成功
			wx.$TUIKit.off(wx.TencentCloudChat.EVENT.SDK_READY, this.onSDKReady,this);
		}).catch((imError) => {
			console.warn('logout error:', imError);
		});
	},
	onSDKReady() {
			const TUIKit = this.selectComponent('#TUIKit');
			TUIKit.init();
	}
});